package vip.meeet.kafka;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class KfkProducer {

//    private static final String TOPIC = "test_topic";
//    private static final String TOPIC = "kfk_topic";
    private static final String TOPIC = "multipar_topic";

    private static final Properties properties = new Properties();

    static {
        // ProducerConfig.BOOTSTRAP_SERVERS_CONFIG
        properties.put("bootstrap.servers", "127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094");
        properties.put("acks", "all");//ISR中所以follower写完消息
        properties.put("retries", 0);//重试0次
        properties.put("batch.size", 16384);//16k，消息累计多少字节向broker发一次消息
        properties.put("linger.ms", 1);//多少毫秒向broker发一次数据
        properties.put("buffer.memory", 33554432);//32M，消息缓冲区大小
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    }

    public static void main(String[] args) throws InterruptedException {
//        sendData();
        sendDataWithCallback();
    }

    private static void sendDataWithCallback() throws InterruptedException {
        while (true){
            Producer<String, String> producer;
            producer = new KafkaProducer<>(properties);
            for (int i = 0; i < 100; i++) {
                String msg = "sendDataWithCallback_" + i;
                ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, msg);
                producer.send(record, new Callback() {
                    @Override
                    public void onCompletion(RecordMetadata metadata, Exception exception) {
                        if(exception != null){
                            System.err.println(exception.getMessage());
                            exception.printStackTrace();
                        }else {
                            System.out.println(metadata.partition() + "--" + metadata.offset());
                        }
                    }
                });
            }
            TimeUnit.SECONDS.sleep(5);
        }
    }

    private static void sendData(){
        Producer<String, String> producer = null;
        try {
            producer = new KafkaProducer<>(properties);
            for (int i = 0; i < 100; i++) {
                String msg = "sendData_" + i;
                ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, msg);
                producer.send(record);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.close();
        }
    }

}
